<?php

namespace App\Http\Controllers\Admin;

use Validator;
use App\FocusImg;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FocusImgController extends Controller
{
    public function index(Request $request)
    {
        $focusImgs = FocusImg::orderBy('created_at', 'desc')
            ->get();
        return view('admin.focus_img.index', [
            'request' => $request,
            'focusImgs' => $focusImgs
        ]);
    }

    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->except(['_token']);
            $rules = [
                'attachment1' => 'required'
            ];
            $messages = [
                'attachment1.required' => '请上传焦点图！'
            ];
            $validator = Validator::make($data, $rules, $messages);
            if ($validator->fails()) {
                $return = [
                    'code' => __LINE__,
                    'msg' => $validator->errors()->first()
                ];
                return response()->json($return);
            }
            $fileArr = explode(',', rtrim($data['attachment1'], ','));
            foreach ($fileArr as $file) {
                $focusImg = new FocusImg();
                $focusImg->name = $file;
                $focusImg->save();
            }
            $return = ['code' => 0];
            return response()->json($return);
        }
        return view('admin.focus_img.add', [
            'request' => $request
        ]);
    }

    public function del(Request $request)
    {
        $id = $request->input('id');
        $focusImg = FocusImg::find($id);
        $file = 'upload/' . iconv('utf-8', 'gbk', $focusImg->name);
        if (is_file($file)) {
            unlink($file);
        }
        if ($focusImg->delete()) {
            $return = ['code' => 0];
        } else {
            $return = [
                'code' => __LINE__,
                'msg' => '删除失败，请稍后重试！'
            ];
        }
        return response()->json($return);
    }
}